package com.woniuxy.uums.controller;

import com.woniuxy.common.utils.ResponseUtil;
import com.woniuxy.uums.dto.SendVerificationCodeDto;
import com.woniuxy.uums.dto.VerificationCodeLoginDto;
import com.woniuxy.uums.service.SmsService;
import com.woniuxy.uums.service.WcnUserService;
import com.woniuxy.uums.util.RedisUtil;
import com.woniuxy.uums.util.SmsUtil;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 验证码登录控制器
 * @author yolo
 * @date Created in 2025/1/17 10:01
 * @description 验证码登录相关接口
 * @modified By：
 * @version: $
 */
@RestController
@RequestMapping("/verification")
@AllArgsConstructor
public class VerificationCodeController {
    
    private final SmsService smsService;
    private final WcnUserService wcnUserService;
    private final RedisUtil redisUtil;
    
    /**
     * 发送验证码
     * @param request 发送验证码请求
     * @return 发送结果
     */
    @PostMapping("/send-code")
    public ResponseUtil sendVerificationCode(@Valid @RequestBody SendVerificationCodeDto request) {
        String phone = request.getPhone();
        
        // 1. 检查手机号格式
        if (!SmsUtil.isValidPhone(phone)) {
            return ResponseUtil.error("手机号格式不正确");
        }
        
        // 2. 检查发送频率限制
        if (!redisUtil.canSendVerificationCode(phone)) {
            return ResponseUtil.error("发送过于频繁，请稍后再试");
        }
        
        // 3. 检查用户是否存在
        if (wcnUserService.getUserByPhone(phone) == null) {
            return ResponseUtil.error("该手机号未注册");
        }
        
        // 4. 生成验证码
        String code = SmsUtil.generateVerificationCode();
        
        // 5. 发送短信
        boolean sendResult = smsService.sendVerificationCode(phone, code);
        if (!sendResult) {
            return ResponseUtil.error("短信发送失败，请稍后重试");
        }
        
        // 6. 保存验证码到Redis
        redisUtil.saveVerificationCode(phone, code);
        
        // 7. 设置发送频率限制
        redisUtil.setSendLimit(phone);
        
        return ResponseUtil.success("验证码发送成功");
    }
    
    /**
     * 验证码登录
     * @param request 验证码登录请求
     * @return 登录结果
     */
    @PostMapping("/login")
    public ResponseUtil loginByVerificationCode(@Valid @RequestBody VerificationCodeLoginDto request) {
        String phone = request.getPhone();
        String code = request.getCode();
        
        // 1. 验证码登录
        String token = wcnUserService.loginByVerificationCode(phone, code);
        if (token == null) {
            return ResponseUtil.error("验证码错误或已过期");
        }
        
        return ResponseUtil.success(token);
    }
} 